package com.xoa.service.equipment.impl;

import com.xoa.controller.enclosure.EnclosureController;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.equipment.*;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.department.Department;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.equipment.*;
import com.xoa.model.users.Users;
import com.xoa.service.equipment.EquipmentService;
import com.xoa.util.LimsJson;
import com.xoa.util.ToJson;
import com.xoa.util.UserUtil;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;

import com.xoa.util.page.PageParams;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class EquipmentServiceImpl implements EquipmentService {
    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private EquipTypeMapper equipTypeMapper;

    @Autowired
    private EquipCapyMapper equipCapyMapper;

    @Autowired
    private EquipmentCapysMapper equipmentCapysMapper;

    /*@Autowired
    private LimsBaseService limsBaseService;
*/
    @Autowired
    private LimsEquipEventsPlanMapper limsEquipEventsPlanMapper;

    @Autowired
    private LimsEquipExperienceMapper experienceMapper;

    @Autowired
    private LimsCommonCodeMapper limsCommonCodeMapper;

    @Autowired
    private EquipmentTransferServiceImpl equipmentTransferServiceImpl;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Resource
    private UsersMapper usersMapper;

    @Autowired
    private AttachmentMapper attachmentMapper;

    @Autowired
    private EnclosureController enclosureController;

    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Override
    public LimsJson<Equipment> selectAllEquipment(HttpServletRequest request, Integer page, Integer pageSize, Boolean userFlag, Integer equipTypeId, String column, String inptext) {
        LimsJson limsJson = new LimsJson(1, "查询失败");
        List<Equipment> equipment = new ArrayList<>();
        Map map = new HashMap();
        Map map1 = new HashMap();
        int count = 0;
        //封装分页参数
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(true);
        pageParams.setPage(Integer.valueOf(request.getParameter("page")));
        pageParams.setPageSize(Integer.valueOf(request.getParameter("limit")));
        map.put("pageParams", pageParams);
        Users users = UserUtil.getUser(request);
        if (column != null && inptext != null) {
            if (column.equals("EQUIP_STATUAS_CODE") || column.equals("PROPERTY_CODE")) {
                List<SysCode> sysCodes = sysCodeMapper.searchLike(inptext);
                String codes = "";
                for (SysCode code : sysCodes) {
                    codes += code.getCodeNo() + ",";
                }
                String key = equipmentTransferServiceImpl.lineToHump(column);
                map.put("column", column);
                map.put("smcolums", key);
                map.put("columsValue", codes.split(","));
                map1.put("column", column);
                map1.put("smcolums", key);
                map1.put("columsValue", codes.split(","));
            } else {
                if(!column.equals("EQUIP_NO")&&
                        !column.equals("EQUIP_NAME")&&
                        !column.equals("MODEL_NO")&&
                        !column.equals("SPEC")&&
                        !column.equals("MANUFACTURER")&&
                        !column.equals("SUPPLIER")&&
                        !column.equals("FACTORY_NO")&&
                        !column.equals("CLOUD_SN")&&
                        !column.equals("DEPT_NAME")){
                    limsJson.setMsg("参数错误");
                    return limsJson;
                }
                map.put("column", column);
                map.put("inptext", inptext);
                map1.put("column", column);
                map1.put("inptext", inptext);
            }
        }
        String deptExp = "";
        Integer deptId = users.getDeptId();
        deptExp = deptExp +deptId;
                map.put("deptExps", deptExp.split(","));
        //List<EquipType> equipTypeList = equipTypeMapper.selectChildEquipType(equipTypeId);
        List<Integer> equipIdNode = equipTypeMapper.selectTypeNode(equipTypeId);
        equipIdNode.add(equipTypeId);
        if (equipIdNode.size() > 0) {
            String ids = "";
            for (Integer equipTeId : equipIdNode) {
                ids = ids + equipTeId + ",";
            }
            if (ids.length() > 0) {
                String[] typeIds = ids.split(",");
                map.put("typeIds", typeIds);
                equipment = equipmentMapper.selectAllEquipment(map);
                map1.put("typeIds", typeIds);
                map1.put("deptExps", deptExp.split(","));
                if(column!=null&&column!=""&&column.equals("DEPT_NAME")){
                    map1.put("deptExps", deptExp.split(","));
                    List<Equipment> equipmentList = equipmentMapper.selectById(map1);
                    count = equipmentList.size();
                }else {
                    int i = equipmentMapper.countAllEquipment(map1);
                    count = i;
                }
            }
        } else if(column!=null&&column!=""&&column.equals("DEPT_NAME")){
            if(column.equals("DEPT_NAME")){
                equipment = equipmentMapper.selectAllEquipment(map);
                map1.put("deptExps", deptExp.split(","));
                List<Equipment> equipmentList = equipmentMapper.selectById(map1);
                count = equipmentList.size();
            }
        }else {
            map.put("equipTypeId", equipTypeId);
            equipment = equipmentMapper.selectAllEquipment(map);
            map1.put("equipTypeId", equipTypeId);
            map1.put("deptExps", deptExp.split(","));
            int i = equipmentMapper.countAllEquipment(map1);
            count = i;
        }
        try {
            //int cont = equipmentMapper.countAllEquipment();
            //equipment = equipmentMapper.selectAllEquipment(map);
            for (Equipment e : equipment) {
                //以下五个if是将数据库中存储的id'赋值为commonCode中的CodeTypeName
                //在这里也可以用一个for循环，将查询出来的设备信息中的commonCodeid用一个字符串串起来，
                // 转化成一个字符数组，循环处理数组即可实现以下功能
                if (e.getEquipStatuasId() != null && !e.getEquipStatuasId().equals("")) {
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getEquipStatuasId(),null);
                    if (equipCapy != null && !equipCapy.equals("")) {
                        e.setEquipStatusCode(e.getEquipStatuasId());
                        e.setEquipStatuasId(equipCapy.getCodeTypeName());

                    }
                }
                if (e.getPhyQuantiId() != null && !e.getPhyQuantiId().equals("")) {
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getPhyQuantiId(),null);
                    if (equipCapy != null && !equipCapy.equals("")) {
                        e.setPhyQuantiId(equipCapy.getCodeTypeName());
                    }
                }
                if (e.getCouplingId() != null && !e.getCouplingId().equals("")) {
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getCouplingId(),null);
                    if (equipCapy != null && !equipCapy.equals("")) {
                        e.setCouplingId(equipCapy.getCodeTypeName());
                    }
                }
                if (e.getDirectionId() != null && !e.getDirectionId().equals("")) {
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getDirectionId(),null);
                    if (equipCapy != null && !equipCapy.equals("")) {
                        e.setDirectionId(equipCapy.getCodeTypeName());
                    }
                }
                if (e.getPropertyId() != null && !e.getPropertyId().equals("")) {
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getPropertyId(),"PROPERTY_OWNER");
                    if (equipCapy != null && !equipCapy.equals("")) {
                        e.setPropertyId(equipCapy.getCodeTypeName());
                    }
                }
                if (e.getSourceAssets() != null && !e.getSourceAssets().equals("")) {
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getSourceAssets(),null);
                    if (equipCapy != null && !equipCapy.equals("")) {
                        e.setSourceAssets(equipCapy.getCodeTypeName());
                    }
                }
                if (e.getStandMateYn() != null && !e.getStandMateYn().equals("")) {
                    if (e.getStandMateYn().equals("0")) {
                        e.setStandMateYn("否");
                    } else {
                        e.setStandMateYn("是");
                    }
                }
            }
            if (equipment.size() > 0) {
                limsJson.setCount(count);
                limsJson.setMsg("查询到" + count + "条数据");
                limsJson.setCode(0);
                limsJson.setData(equipment);
            } else {
                limsJson.setMsg("查询无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return limsJson;
    }

    @Override
    public LimsJson<Equipment> selectEquipmentByEquipTypeId(HttpServletRequest request, Integer equipTypeId) {
        LimsJson limsJson = new LimsJson(1, "err");
        List<Equipment> equipments = equipmentMapper.selectByEquipTypeId(equipTypeId);
        if (equipments.size() > 0) {
            limsJson.setCount(equipments.size());
            limsJson.setMsg("查询到" + equipments.size() + "条数据");
            limsJson.setCode(0);
            limsJson.setData(equipments);
        } else {
            limsJson.setMsg("查询失败");
        }
        return limsJson;
    }

    @Override
    public LimsJson<Equipment> selectEquipmentByEquipId(HttpServletRequest request, Integer equipId) {
        LimsJson limsJson = new LimsJson(1, "err");

        Equipment equipment = equipmentMapper.selectByPrimaryKey(equipId);
        EquipType equipType = equipTypeMapper.selectByPrimaryKey(equipment.getEquipTypeId());
        EquipType equipType1 = equipTypeMapper.selectByPrimaryKey(equipType.getEquipTypePid());
        equipment.setParentTypeName(equipType1.getLabel());

        if (equipment != null) {
            limsJson.setObject(equipment);
            limsJson.setMsg("ok");
            limsJson.setCode(0);
        } else {
            limsJson.setMsg("查询失败");
        }
        return limsJson;
    }

    @Override
    public LimsJson<Equipment> addEquipment(HttpServletRequest request, Equipment equipment) {
        LimsJson limsJson = new LimsJson(1, "err");
        try {
            if (equipment != null) {
                EquipType equipType = equipTypeMapper.selectByPrimaryKey(equipment.getEquipTypeId());
                String[] ids = null;
                if (equipType != null && equipType.getCapyIds() != null && !equipType.getCapyIds().equals("")) {
                    //获取该设备对应类型下能力项
                    ids = equipType.getCapyIds().split(",");
                }


                SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
                sdf.applyPattern("yyyy-MM-dd");
                equipment.setRecordDate(new Date());//入账时间为当前默认时间

                int i = equipmentMapper.insertSelective(equipment);//新建设备接口
                int flag = 0;
                //这个循环是向capys表中存储数据，
//                if (ids != null && !ids.equals("")) {
//                    for (int j = 0; j < ids.length; j++) {
//                        EquipmentCapys equipmentCapys = new EquipmentCapys();
//                        equipmentCapys.setCapyId(Integer.parseInt(ids[j]));
//                        equipmentCapys.setEquipId(equipment.getEquipId());
//
//                        equipmentCapysMapper.insertSelective(equipmentCapys);//设备能力项接口
//                        flag++;
//                    }
//                }
                if (i > 0) {
                    limsJson.setCode(0);
                    limsJson.setMsg("插入成功");
                    limsJson.setObject(equipment);
                    limsJson.setCount(flag);
                } else {
                    limsJson.setMsg("插入失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return limsJson;
    }

    @Override
    public LimsJson<Equipment> editEquipment(HttpServletRequest request, Equipment equipment, Integer equipId) {
        LimsJson limsJson = new LimsJson(1, "err");
        try {
            int i = equipmentMapper.updateByPrimaryKeySelective(equipment);
            if (i > 0) {
                limsJson.setCode(0);
                limsJson.setMsg("修改成功");
                limsJson.setObject(equipment);
                limsJson.setCount(i);
            } else {
                limsJson.setMsg("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return limsJson;
    }

    @Override
    public LimsJson<Equipment> deleteEquipment(HttpServletRequest request, Integer equipId) {
        LimsJson limsJson = new LimsJson(1, "err");
        try {
            int i = equipmentMapper.deleteByPrimaryKey(equipId);
            if (i > 0) {
                limsJson.setCode(0);
                limsJson.setMsg("删除成功");
                limsJson.setCount(i);
            } else {
                limsJson.setMsg("删除失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return limsJson;
    }

    public LimsJson<Equipment> deleteArrayEquipment(HttpServletRequest request, String equipIds) {
        LimsJson limsJson = new LimsJson(1, "err");
        String[] idArray = equipIds.split(",");
        try {
            for (int i = 0; i < idArray.length; i++) {

                    int mes = equipmentMapper.deleteByPrimaryKey(Integer.parseInt(idArray[i]));
                    if (mes > 0) {
                        limsJson.setCode(0);
                        limsJson.setMsg("删除成功");
                    } else {
                        limsJson.setMsg("删除失败");
                    }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return limsJson;
    }

    public LimsJson<Object> editArrayEquipment(String json) {
        LimsJson limsJson = new LimsJson(1, "err");
        if (json != null) {
            JSONArray jsonarray = JSONArray.fromObject(json);
            List<Equipment> equipmentList = (List<Equipment>) JSONArray.toCollection(jsonarray, Equipment.class);
            if (equipmentList != null && equipmentList.size() > 0) {
                int i = 0;
                for (Equipment equipment : equipmentList) {
                    if (equipment != null && equipment.getEquipId() != null) {
                        equipmentMapper.updateByPrimaryKeySelective(equipment);
                    }
                }
                i++;
                if (equipmentList.size() == i) {
                    limsJson.setCode(0);
                    limsJson.setMsg("修改成功");
                }

            } else {
                limsJson.setMsg("请填写完整信息");
            }
        } else {
            limsJson.setMsg("请填写完整信息");
        }
        return limsJson;
    }

    //这是一个在设备详情中得一个同步能力值，同步的单词属于敏感单词，用together代替，
    public LimsJson<Object> togetherEquipCapy(Integer equipId) {
        LimsJson limsJson = new LimsJson(1, "err");
        try {
            if (equipId != null && !equipId.equals("")) {
                String ids = "";//这个ids记录设备类型下的能力项
                Equipment equipment = equipmentMapper.selectByPrimaryKey(equipId);
                if (equipment != null && equipment.getEquipTypeId() != null) {
                    //因为能力项时从设备类型下同步过来的，所以在这里找寻该设备下的类型，从而找到能力项id
                    EquipType equipType = equipTypeMapper.selectByPrimaryKey(equipment.getEquipTypeId());
                    if (equipType != null && equipType.getCapyIds() != null) {
                        ids = equipType.getCapyIds();
                    }
                }
                String[] capyId = null;
                if (ids != null && !ids.equals("")) {//判断设备类型下是否有capyids
                    capyId = ids.split(",");//这个数组是记录设备类型下的capyid
                    //查询某个设备下的所有能力项
                    List<EquipmentCapys> equipmentCapys = equipmentCapysMapper.selectByEquipId(equipId);
                    if (equipmentCapys != null && equipmentCapys.size() > 0) {//判断设备下是否有capyids，若果有执行if，没有执行else
                        String newIds = "";
                        for (EquipmentCapys epc : equipmentCapys) {
                            //遍历能力项，取出他的capyid 以前需求是可以删除以前的能力项，
                            // 现在不可以，所以注释掉下列代码
                            if (Arrays.asList(capyId).contains(epc.getCapyId().toString()) == false) {
                                equipmentCapysMapper.deleteByPrimaryKey(epc.getId());
                            } else {
                                //遍历能力项，记录capyid
                                newIds += epc.getCapyId() + ",";
                            }
                        }
                        if (!newIds.equals("") && newIds != null) {
                            int res = 0;//记录同步次数
                            int els = 0;//记录不同步次数
                            String[] newcapyId = newIds.split(",");//记录设备的能力项id

                            for (int j = 0; j < capyId.length; j++) {
                                if (Arrays.asList(newcapyId).contains(capyId[j]) == false) {//判断同步的capyid在不在以前的信息中,不再新增，在记录次数
                                    EquipmentCapys epcs = new EquipmentCapys();
                                    epcs.setEquipId(equipId);
                                    epcs.setCapyId(Integer.parseInt(capyId[j]));
                                    int m = equipmentCapysMapper.insert(epcs);
                                    if (m > 0) {
                                        res++;
                                    }
                                } else {
                                    els++;
                                }
                            }
                            if (res > 0) {
                                limsJson.setCode(0);
                                limsJson.setMsg("新增成功");
                            }
                            if (els == capyId.length) {
                                limsJson.setCode(0);
                                limsJson.setMsg("该设备都具有选中能力");
                            }
                        } else {
                            for (int i = 0; i < capyId.length; i++) {
                                EquipmentCapys equipmentCapys1 = new EquipmentCapys();
                                equipmentCapys1.setCapyId(Integer.parseInt(capyId[i]));
                                equipmentCapys1.setEquipId(equipId);
                                equipmentCapysMapper.insert(equipmentCapys1);

                                limsJson.setCode(0);
                                limsJson.setMsg("同步成功");
                            }
                        }
                    } else {
                        for (int j = 0; j < capyId.length; j++) {//这个else表示该设备没有一条能力项的情况下执行的操作
                            EquipmentCapys epcs = new EquipmentCapys();
                            epcs.setEquipId(equipId);
                            epcs.setCapyId(Integer.parseInt(capyId[j]));
                            equipmentCapysMapper.insert(epcs);

                            limsJson.setCode(0);
                            limsJson.setMsg("新增成功");
                        }
                    }
                } else {
                    limsJson.setMsg("该设备对应类型无能力项!");
                }
            } else {
                limsJson.setMsg("请选择设备!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            limsJson.setMsg("系统错误!");
        }

        return limsJson;
    }

    public LimsJson editEquipCapyValue(String equipCapyValueJson) {
        LimsJson limsJson = new LimsJson(1, "err");
        //修改多条用json接收，以下是处理json
        if (equipCapyValueJson != null && !equipCapyValueJson.equals("")) {
            JSONArray jsonarray = JSONArray.fromObject(equipCapyValueJson);
            List<EquipmentCapys> list = (List<EquipmentCapys>) JSONArray.toCollection(jsonarray, EquipmentCapys.class);
            int res = 0;
            for (EquipmentCapys equipmentCapys : list) {
                int i = equipmentCapysMapper.updateByPrimaryKeySelective(equipmentCapys);
                if (i > 0) {//修改成功一条记录一次
                    res++;
                }
            }
            if (res == list.size()) {//修改成功次数==list的大小，说明全部修改成功
                limsJson.setCode(0);
                limsJson.setMsg("修改成功");
            }
        } else {//json为空，信息有问题，重新填写
            limsJson.setMsg("请填写正确信息！");
        }
        return limsJson;
    }

    /**
     * 创建作者:   李 然
     * 创建日期:   10:41 2019/9/21
     * 方法介绍:   根据设备类型编号和结算组织查询设备（平板）
     * 参数说明:   * @param typeNo
     *
     * @return com.xoa.util.LimsJson
     */
    @Override
    public LimsJson getEquipByTypeNoAndExpId(String typeNo) {
        LimsJson limsJson = new LimsJson(1, "err");
        /*if (typeNo != null) {
            LimsDeptExp limsDeptExp = DeptExpUtil.getLimsDeptExp();
            //如果为null代表平板结算组织不存在，可能失效
            if (limsDeptExp == null) {
                limsJson.setMsg("未找到当前登陆人员的结算组织，请重新登录尝试！");
            }
            limsDeptExp.setDeptId(17);
            Map map = new HashMap();
            map.put("deptId", limsDeptExp.getDeptId());
            map.put("typeNo", typeNo);
            List<Equipment> equipmentList = equipmentMapper.getEquipByTypeNoAndExpId(map);
            if (equipmentList.size() > 0) {
                limsJson.setCode(0);
                limsJson.setMsg("ok");
                limsJson.setData(equipmentList);
                limsJson.setObject(limsDeptExp.getDeptId());
            } else {
                limsJson.setMsg("暂无设备");
            }
        } else {
            limsJson.setMsg("未传入类型编号");
        }*/
        return limsJson;
    }


    /**
     * 创建作者:   陈东虎
     * 创建日期:   16：:14 2019/11/11
     * 方法介绍:   根据下拉框设备表字段 模糊查询
     * 参数说明:   * @param FieldName FieldValue
     *
     * @return com.xoa.util.LimsJson
     */
    @Override
    public LimsJson selectEquipByField(String fieldName, String fieldValue, Integer page, Integer limit, Integer equipTypeId) {
        LimsJson limsJson = new LimsJson(1, "err");
        List<Equipment> equipmentList = new ArrayList<>();
        Map map = new HashMap();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(true);
        pageParams.setPage(Integer.valueOf(page));
        pageParams.setPageSize(Integer.valueOf(limit));
        if(fieldName!=null&&!fieldName.equals("EQUIP_NO")&&
                !fieldName.equals("EQUIP_NAME")&&
                !fieldName.equals("CODE_TYEP_NAME")&&
                !fieldName.equals("MODEL_NO")&&
                !fieldName.equals("SPEC")&&
                !fieldName.equals("MANUFACTURER")&&
                !fieldName.equals("SUPPLIER")&&
                !fieldName.equals("PROPERTY_CODE")&&
                !fieldName.equals("FACTORY_NO")
               ){
            limsJson.setMsg("参数错误");
            return limsJson;
        }
        map.put("pageParams", pageParams);
        map.put("fieldName", fieldName);
        map.put("fieldValue", fieldValue);
        map.put("equipTypeId", equipTypeId);
        int count = 0;
        equipmentList = equipmentMapper.selectEquipByField(map);
        for (Equipment e : equipmentList) {
            if (e.getCodeName() != null && !e.getCodeName().equals("")) {
                e.setEquipStatuasId(e.getCodeName());
            }
        }
        count = pageParams.getTotal();
        if (equipmentList.size() > 0) {
            limsJson.setMsg("查询成功,查询到" + count + "条数据");
            limsJson.setCode(0);
            limsJson.setData(equipmentList);
            limsJson.setCount(count);
        } else {
            limsJson.setMsg("未找到数据");
        }
        return limsJson;
    }

    /*
     * 创建作者 陈东虎
     * 创建日期 2019/11/21 14:45
     * 方法介绍
     * 参数说明
     * @return LimsJson
     */
    @Override
    public LimsJson<Equipment> getEquipInfoByequipId(Integer equipTypeId) {
        LimsJson limsJson = new LimsJson(1, "err");
        List<String> EquipFailureList = new ArrayList<>();//设备故障分类
        //EquipFailureList=experienceMapper.getEquipFailure();
        Equipment equipment = equipmentMapper.getEquipInfoByequipId(equipTypeId);
        if (equipment != null) {
            limsJson.setCode(0);
            //limsJson.setData(EquipFailureList);
            limsJson.setObj(equipment);
            limsJson.setMsg("查询成功");
        } else {
            limsJson.setMsg("查询失败");
        }
        return limsJson;
    }

    /*
     * 创建作者:   杨 岩 林
     * 创建日期:   15:49 2019/12/19
     * 方法介绍:
     * 参数说明:   * @param ids
     * @return
     */
    public LimsJson<Equipment> getEquipByIds(String ids) {
        LimsJson limsJson = new LimsJson(1, "err");
        Map map = new HashMap();
        String[] idArray = ids.split(",");
        List<Equipment> equipmentList = equipmentMapper.selectByIds(idArray);
        if (equipmentList != null && equipmentList.size() > 0) {
            for (Equipment e : equipmentList) {
                if (e.getEquipStatuasId() != null && !e.getEquipStatuasId().equals("")) {
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getEquipStatuasId(),null);
                    if (equipCapy != null && !equipCapy.equals("")) {
                        e.setEquipStatusCode(e.getEquipStatuasId());
                        e.setEquipStatuasId(equipCapy.getCodeTypeName());

                    }
                }
            }
            limsJson.setMsg("查询成功");
            limsJson.setCode(0);
            limsJson.setData(equipmentList);
        }
        return limsJson;
    }

    /**
     *
     * @作者 李卫卫
     * @创建日期 17:06 2020/7/14
     * @类介绍  获取点击部门下的用户以及子部门用户
     * @参数
     * @return limsJson
     */

    @Override
    public ToJson<Users> getNewChDept(HttpServletRequest request, Integer deptId) {
        ToJson<Users> json = new ToJson<Users>();
        try {
            //查出全部部门的集合
            List<Department> departmentList = new ArrayList<Department>();
            departmentList = departmentMapper.getDatagrid();
            StringBuffer stringBuffer = new StringBuffer();
            //递归
            String deptIds = NewRecursionSelectDept(deptId, stringBuffer, departmentList);
            Department deptById = departmentMapper.getDeptById(deptId);
            List<Users> userByDeptId = new ArrayList<Users>();
            if (!StringUtils.checkNull(deptIds)) {
                String removeStr = StringUtils.getRemoveStr(deptIds);
                String[] split = removeStr.split(",");
                //userByDeptId = usersMapper.selectUserByDeptIds(split);
                userByDeptId = usersMapper.selectUserByDeptIdinfo(split);
                if (userByDeptId != null && userByDeptId.size() > 0) {
                    for (Users u : userByDeptId) {
                        u.setDeptId(deptById.getDeptId());
                        u.setDeptName(deptById.getDeptName());
                    }
                }
            }
            json.setObj(userByDeptId);
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            L.e(e);
            json.setFlag(1);
            json.setMsg("err:" + e);
        }
        return json;
    }

    /**
     *
     * @作者 李卫卫
     * @创建日期 17:36 2020/7/14
     * @类介绍 获取当前登录人部门
     * @参数
     * @return limsJson
     */

    @Override
    public LimsJson getDeptExp(HttpServletRequest request) {
        LimsJson limsJson = new LimsJson(1,"err");                                      //封装返回数据工具
        List list = new ArrayList<>();
        Users user = UserUtil.getUser(request);
        //List deptExpList = limsBaseService.baseGetDeptExpsByUserId(user.getUserId());              //调用com.xoa.lims.basemapper.service中根据userId查询该用户所属结算组织方法
        //通过用户查找部门
        if(user!=null) {
            Integer deptId = user.getDeptId();
            String deptIdOther = user.getDeptIdOther();
            if (!StringUtils.checkNull(deptIdOther)) {
                deptIdOther = deptId + "," + deptIdOther;
            } else {
                deptIdOther = deptId + ",";
            }
            String[] deptIds = deptIdOther.split(",");

            List<Department> departments = departmentMapper.selDeptByIds(deptIds);

            list.add(user);
            list.add(departments);
            limsJson.setObj(list);
            limsJson.setCode(0);
            limsJson.setMsg("查询成功！");
        }
        return limsJson;
    }

    @Override
    public LimsJson selectAttchUrl(String attachId, HttpServletRequest request, String model) {
        LimsJson limsJson=new LimsJson(1,"err");
        if(!StringUtils.checkNull(attachId)){
            String sqlType = (String) request.getSession().getAttribute(
                    "loginDateSouse");
            if(StringUtils.checkNull(sqlType)){
                sqlType="xoa1001";
            }else{
                sqlType="xoa" +sqlType;
            }
            String aid=attachId.split("@")[0];
            Attachment attachment = attachmentMapper.selectByPrimaryKey(Integer.parseInt(aid));
            if(attachment!=null){
                String attUrl = "AID=" + attachment.getAid() + "&" + "MODULE=" + model + "&" + "COMPANY=" + sqlType + "&" + "YM=" + attachment.getYm() + "&" + "ATTACHMENT_ID=" + attachment.getAttachId() + "&" +
                        "ATTACHMENT_NAME=" + attachment.getAttachName();
                limsJson.setCode(0);
                limsJson.setMsg("ok");
                limsJson.setObject(attUrl);
            }else{
                limsJson.setMsg("未找到数据");
            }
        }
        return limsJson;
    }

    @Override
    public void download(HttpServletRequest request, HttpServletResponse response, String attendId, String model) {
        if(!StringUtils.checkNull(attendId)){
            String sqlType = (String) request.getSession().getAttribute(
                    "loginDateSouse");
            if(StringUtils.checkNull(sqlType)){
                sqlType="xoa1001";
            }else{
                sqlType="xoa" +sqlType;
            }
            String aid=attendId.split("@")[0];
            Attachment attachment =attachmentMapper.selectByPrimaryKey(Integer.parseInt(aid));
            if(attachment!=null){
                try {
                    enclosureController.download(attachment.getAid(),model,attachment.getYm(),attachment.getAttachId(),sqlType,null,response,request);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public String NewRecursionSelectDept(int deptId, StringBuffer stringBuffer, List<Department> departments) {
        stringBuffer.append(deptId + ",");
        String returnStr = new String();

        List<Department> childList = new ArrayList<Department>();
        for (Department department : departments) {
            if (department.getDeptParent() == deptId) {
                stringBuffer.append(department.getDeptId() + ",");
                childList.add(department);
            }
        }
        for (Department department : childList) {
            NewRecursionSelectDept(department.getDeptId(), stringBuffer, departments);
        }
        if (!StringUtils.checkNull(stringBuffer.toString())) {
            returnStr = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
        }
        return returnStr;
    }
}
